package cn.com.zpark.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @PackageName: cn.com.zpark.jdbc.utils
 * @ClassName: JDBCUtils
 * @Description:JDBC工具类,注册驱动，获取连接，关闭连接
 * @author: RZS
 * @date: 2021/10/26  17:38
 */
public class JDBCUtils01 {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    // 初始化数据
    static {
        // 创建properties集合
        Properties properties = new Properties();
        // 加载文件
        InputStream inputStream = JDBCUtils01.class.getClassLoader().getResourceAsStream("jdbcutils.properties");

        try {
            // 加载流对象
            properties.load(inputStream);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取连接对象
     * @return
     * @throws Exception
     */
    public static Connection getConn() throws Exception {
        // 注册驱动，获取连接，返回连接对象
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }

    /**
     * 关闭连接
     */
    public static void close(ResultSet res, Statement stat, Connection conn){
        if(res != null){
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stat != null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
